import React, { useEffect, useState } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
//引入标记点的数据
import { marker } from '../../data/map/'
import s from './index.module.scss'
import { ty, fp, fw, mc, change,location } from '../../asstes/map'
import axios from 'axios'
//import { requestIp } from './tools';
export default function GDMap(props: any) {
    let { show, value,poisList,setPoisList} = props
    // console.log(value,'---');
    let initList:any[] =[]
    //let [poisList,setPoisList] = useState(initList) 
    //console.log(show,'---');

    let img = [change, mc, ty, fw, fp]
    //用来记录初次加载时地图的中心
    let center = {}
    let map: any = null
   
    let createMarker = function (AMap: any, markers: any) {
        //绘制icon放外面 减少绘制次数 优化
        let iconList = img.map((i: any) => {
            let icon = new AMap.Icon({
                size: new AMap.Size(50, 50),    // 图标尺寸
                image: i,  // Icon的图像
                imageSize: new AMap.Size(50, 50)   // 根据所设置的大小拉伸或压缩图片
            });
            return icon
        })
        let markerList = markers.map((i: any) => {
            if (show[i.type - 1]) {
                return new AMap.Marker({
                    position: new AMap.LngLat(i.longitude, i.latitude),
                    icon: iconList[i.type - 1],
                    zoom: 13
                })
            }
        })
        return markerList.filter((item: any) => item)
    }
    let initMap = (res: { x: string, y: string }) => {
        AMapLoader.load({
            key: "91eea649e143bd1ecdf7708d0630c61d",      // 申请好的Web端开发者Key，首次调用 load 时必填
            version: "2.0",         // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            plugins: [''],          // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            AMapUI: {
                version: "1.1",
                plugins: ["overlay/SimpleMarker"]
            }
        }).then((AMap: any) => {
            map = new AMap.Map("container", { //设置地图容器id
                viewMode: "3D",         //是否为3D地图模式
                zoom: 10,                //初始化地图级别
                center: [Number(res.y), Number(res.x)], //初始化地图中心点位置
            }
            );

            center = map.getCenter() //拿到地图的中心
            map.add(createMarker(AMap, marker))
        }).catch(e => {
            // console.log(e,'aaaa');
        })
    }
    const config = {
        timeout: 10000,
        baseURL: '/',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json;charset=UTF-8',
        },
    }
    const instance = axios.create(config);
    // let requestIp = async function () {
    //     let ip = ''
    //     let data = await instance.get('ipShow/cityjson?ie=utf-8', config)
    //     const info = data.data.substring(19, data.data.length - 1)
    //     ip = JSON.parse(info).cip
    //     return ip
    //     //console.log(ip);
    // }
    const getAddress = async function () {
        const data = await instance.get(`https://restapi.amap.com/v3/ip?key=6d1bbc7d246260d6c06cf55bfb01c443`, config)
        let res = data.data
        if (res.status == 1) {
            // console.log(res, '---');
            
            let arr = res.rectangle
            //console.log(arr);
            let spot = {
                y: arr[0] || '116.39039',
                x: arr[2] || '39.930181'
            }
            return spot
        }
    }
    const setConter = () => {
        map.setCenter(center)
    }
    const search = async (value:string)=>{
        const data = await instance.get(`https://restapi.amap.com/v5/place/text?key=6d1bbc7d246260d6c06cf55bfb01c443&keywords=${value}`)
        let pois = [...data.data.pois]
        if(pois.length===0){
            pois=[{massage:'没有搜索结果'}]
        }
         setPoisList(pois)
         return 
        // return pois
        // console.log(pois);
    }
    if(value!==''){
        // console.log(poisList,'---');
        
        if(!poisList.length){
             search(value)
        }
        
    }

    useEffect(() => {
        //手动获取Ip
        // requestIp().then((res)=>{
        //     console.log(typeof res);
        //     getAddress(res)
        // }

        // )
        getAddress().then((res) => {
            //拿到当前位置
            //console.log(res);
            initMap(res as { x: string, y: string })

        })
    })
    return (
        <>
            {/* 设置id是为了挂载地图 */}
            {
                value === '' ?
                <>
                <div id="container" className={s.map}></div>
                <div className={s.location} onClick={()=>{setConter()}}>
                    <img src={location} alt="" />
                </div></>:
                ''
            }
           
        </>
    )
}
